package net.demo.demo4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class TcpClient {
    public static void main(String[] args) {
        final String serverAddress = "localhost"; // 服务端地址
        final int serverPort = 12345; // 服务端端口

        try (
                Socket socket = new Socket(serverAddress, serverPort);
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                OutputStream writer = socket.getOutputStream();
                BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in))
        ) {
            System.out.println("成功连接到服务器");

            String userInput;
            while ((userInput = consoleReader.readLine()) != null) {
                // 发送消息给服务器
                writer.write(userInput.getBytes());
                writer.write('\n');
                writer.flush();

                // 读取服务器的响应
                String serverResponse = reader.readLine();
                if (serverResponse == null) {
                    break;
                }
                System.out.println("服务端回复: " + serverResponse);
            }
        } catch (IOException e) {
            System.err.println("连接异常: " + e.getMessage());
        }
    }
}
